package com.huluobo.sign.view

import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.huluobo.lib_base.BaseTitle
import com.amap.api.maps.AMap
import com.amap.api.maps.MapView
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.lib_base.BaseApp
import com.huluobo.lib_base.UIState
import com.huluobo.sign.SignIntent
import com.huluobo.sign.SignViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Timer
import kotlin.concurrent.timerTask

/**
 *  Created by LC on 2025/2/8.
 */
lateinit var map: AMap//高德地图本体
lateinit var myLocationStyle: MyLocationStyle//定位蓝点
lateinit var mapView: MapView//地图的view
lateinit var geocodeSearch: GeocodeSearch
lateinit var query: RegeocodeQuery


lateinit var timer: Timer

@Composable
fun SignCommitPage(navHostController: NavHostController, vm: SignViewModel = hiltViewModel()) {

    var startTime by remember {
        mutableStateOf("上班还未打卡")
    }

    var endTime by remember {
        mutableStateOf("下班还未打卡")
    }

    var btnName by remember {
        mutableStateOf("上班打卡")
    }

    var nowTime by remember {
        mutableStateOf("00:00:00")
    }

    var enable by remember {
        mutableStateOf(true)
    }

    val kv = MMKV.defaultMMKV()

    var lat = 0.0
    var lon = 0.0
    var type = ""
    var status = ""
    var address = ""

    LaunchedEffect(key1 = "", block = {
        launch {
            timer = Timer()
            timer.schedule(timerTask {
                nowTime = SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis())
            }, 0, 1000)
        }

        launch {
            //取出上班打卡时间
            val signTime = kv.decodeString("sign", "").toString()
            //如果上班打卡不为空,说明打过
            if (!TextUtils.isEmpty(signTime)) {
                val time = SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis())
                val signDate = signTime.substring(0, 10)
                //如果上班打卡日期是今天
                if (time == signDate) {
                    //说明今天上班打卡过,显示上班打卡时间
                    startTime = "上班时间: $signTime"
                    //取出下班时间
                    val outTime = kv.decodeString("out")
                    val outDate = outTime?.substring(0, 10)
                    //如果下班打卡是今天
                    if (time == outDate) {
                        //说明今天下班打卡过,显示下班打卡时间
                        endTime = "下班时间: $outTime"
                        //按钮不可用
                        enable = false
                    } else {
                        //如果下班打卡时间不是今天
                        btnName = "下班打卡"
                    }
                }
            }
        }

        launch {
            vm.state.collect {
                when (it) {
                    is UIState.onError -> {
                        Log.e("TagA", "添加签到信息失败:${it.msg}")
                    }

                    UIState.onLoading -> {}
                    is UIState.onSuccess<*> -> {
                      ToastUtils.showLong("签到/签退成功")
                    }
                }
            }
        }
    })


    Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(10.dp)) {
        BaseTitle(title = "打卡", navHostController = navHostController)
        //这里放地图
        AndroidView(modifier = Modifier.height(300.dp), factory = {
            mapView = MapView(it)//创建view
            mapView.onCreate(null)//在构建view之后,需要在视图上创建view
            map = mapView.map//通过view获取地图本体
            myLocationStyle = MyLocationStyle()//构建导航蓝点
            myLocationStyle.interval(2000)//蓝点刷新时间
            map.myLocationStyle = myLocationStyle//在map上展示拉点
            map.isMyLocationEnabled = true//设置蓝点是否显示
            map.addOnMyLocationChangeListener {
                lon = it.longitude
                lat = it.latitude
                geocodeSearch = GeocodeSearch(BaseApp.context)
                query = RegeocodeQuery(LatLonPoint(it.latitude, it.longitude), 200f, GeocodeSearch.AMAP)
                geocodeSearch.getFromLocationAsyn(query)
                geocodeSearch.setOnGeocodeSearchListener(object : OnGeocodeSearchListener {
                    override fun onRegeocodeSearched(result: RegeocodeResult?, p1: Int) {
                        address = result?.regeocodeAddress?.formatAddress.toString()
                    }

                    override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {
                    }
                })
            }
            mapView//当前方法返回的view
        })

        Spacer(modifier = Modifier.height(50.dp))
        Text(
            text = startTime,
            Modifier
                .fillMaxWidth()
                .padding(start = 20.dp)
        )
        Spacer(modifier = Modifier.height(20.dp))
        Text(
            text = endTime,
            Modifier
                .fillMaxWidth()
                .padding(start = 20.dp)
        )
        Spacer(modifier = Modifier.height(20.dp))
        Button(modifier = Modifier
            .size(140.dp)
            .clip(CircleShape), enabled = enable,
            onClick = {
                val time = SimpleDateFormat("yyyy-MM-dd:HH:mm:ss").format(System.currentTimeMillis())
                if (btnName == "上班打卡") {
                    kv.encode("sign", time)
                    startTime = "上班时间: $time"
                    btnName = "下班打卡"
                    type = "上班"
                    status = "正常"
                    val map = mutableMapOf<String, Any>()
                    map["lat"] = lat
                    map["lon"] = lon
                    map["type"] = type
                    map["status"] = status
                    map["address"] = address
                    vm.sendIntent(SignIntent.addSign(map))
                } else {
                    kv.encode("out", time)
                    endTime = "下班时间: $time"
                    enable = false
                    type = "下班"
                    status = "正常"
                    val map = mutableMapOf<String, Any>()
                    map["lat"] = lat
                    map["lon"] = lon
                    map["type"] = type
                    map["status"] = status
                    map["address"] = address
                    vm.sendIntent(SignIntent.addSign(map))
                }

            }) {
            Column {
                Text(text = btnName, fontSize = 22.sp)
                Text(text = nowTime, fontSize = 22.sp)
            }
        }
    }
}
